# src/ui/tkinter/screens/selection_screen.py
import tkinter as tk
from tkinter import messagebox
from src.core.item_manager import delete_item

def show_selection_screen(parent, items):
    """Show character selection screen"""
    # Clear current interface
    for widget in parent.winfo_children():
        widget.destroy()
    
    # Title
    title = tk.Label(parent, text="📋 Character List", font=("Arial", 20))
    title.pack(pady=20)
    
    # Character list frame
    list_frame = tk.Frame(parent)
    list_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
    
    if not items:
        empty_label = tk.Label(list_frame, text="No characters, click below to add", fg="gray")
        empty_label.pack(pady=50)
    else:
        # Show character list
        for i, item in enumerate(items):
            char_frame = tk.Frame(list_frame, relief=tk.RAISED, bd=1)
            char_frame.pack(fill=tk.X, pady=5)
            
            char_text = f"{i+1}. {item['name']} - {item['type']} (Lv.{item['level']})"
            char_label = tk.Label(char_frame, text=char_text, font=("Arial", 12))
            char_label.pack(side=tk.LEFT, padx=10, pady=5)
            
            # Delete button
            def delete_char(char_id=item["id"]):
                if messagebox.askyesno("Confirm Delete", "Are you sure you want to delete this character?"):
                    delete_item(items,char_id)
                    show_selection_screen(parent, items)
            
            delete_btn = tk.Button(char_frame, text="Delete", command=delete_char, bg="#e74c3c", fg="white")
            delete_btn.pack(side=tk.RIGHT, padx=10)
    
    # Button frame
    button_frame = tk.Frame(parent)
    button_frame.pack(pady=20)
    
    # Add character button
    def add_character():
        from .creation_screen import show_creation_screen
        show_creation_screen(parent, items)
    
    add_btn = tk.Button(button_frame, text="Add Character", command=add_character, bg="#27ae60", fg="white", font=("Arial", 12))
    add_btn.pack(side=tk.LEFT, padx=10)
    
    # Back button
    def back_to_launch():
        from .launch_screen import show_launch_screen
        show_launch_screen(parent, items)
    
    back_btn = tk.Button(button_frame, text="Back", command=back_to_launch, font=("Arial", 12))
    back_btn.pack(side=tk.LEFT, padx=10)